package com.basemodel;

public class DataResult<T> {
    private T data;
    private int code;
    private String msg;
    public static final int SUCCESS_CODE = 0;
    public static final int FAIL_CODE = 999;
    public static final String SUCCESS_MSG = "success";

    public DataResult(T data, int code, String msg) {
        this.data = data;
        this.code = code;
        this.msg = msg;
    }

    public DataResult() {
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public static <T> DataResult<T> doSuccess(T data) {
        return new DataResult(data, SUCCESS_CODE, SUCCESS_MSG);
    }

    /**
     * 使用这个方法构建返回值, 避免形式化参数的原始使用
     *
     * @param errorCode 错误码对象
     * @param msg       错误消息
     * @param <T>       形式化参数，表示dataResult携带的数据类型
     * @return 错误消息 DataResult
     */
    public static <T> DataResult<T> buildError(ErrorCode errorCode, String msg) {
        return new DataResult<>(null, errorCode.getCode(), msg);
    }

    /**
     * 使用这个方法构建返回值, 避免形式化参数的原始使用
     *
     * @param msg 错误消息
     * @param <T> 形式化参数，表示dataResult携带的数据类型
     * @return 错误消息 DataResult
     */
    public static <T> DataResult<T> buildError(String msg) {
        return buildError(ErrorCode.FAIL, msg);
    }

    public static DataResult doFail(String msg) {
        return new DataResult(null, FAIL_CODE, msg);
    }

    public static DataResult doFail(ErrorCode errorCode) {
        return new DataResult(null, errorCode.getCode(), errorCode.name());

    }

    public static <T> DataResult<T> doFail(ErrorCode errorCode, T data) {
        return new DataResult(data, errorCode.getCode(), errorCode.name());
    }

    public static DataResult doFail(int code, String msg) {
        return new DataResult(null, code, msg);
    }

    public static <T> DataResult<T> doFail(T data, ErrorCode errorCode) {
        return new DataResult(data, errorCode.getCode(), errorCode.name());
    }

    public static <T> DataResult<T> doFail(T data, ErrorCode errorCode, String msg) {
        return new DataResult<>(data, errorCode.getCode(), msg);
    }

    @Override
    public String toString() {
        return "DataResult{" +
                "data=" + data +
                ", code=" + code +
                ", msg='" + msg + '\'' +
                '}';
    }
}